<project basedir=".">
    <!--
    IMPORTANT: This file is private and should not be edited.
    -->
    <import file="${cmd.config.dir}/plugin.xml"/>

    <target name="init-properties">
        <!--init the defualt app path here-->
        <property name="args.path" location="${basedir}/../../"/>
        <property name="templates.dir"
                  location="${framework.config.dir}/templates"/>

    </target>

    <!--
        Copies select files from the base sdk directory into the  new application
        directory structure
    -->
    <target name="copy-framework-to-workspace-impl">
        <property name="framework.target.dir" location="${framework.path}"/>
        <copy todir="${framework.target.dir}">
            <fileset dir="${framework.dir}"
                     includes="src/**/*,
                               microloader/**/*,
                               resources/**/*,
                               cmd/**/*,
                               version.txt,
                               sencha-touch-debug.js,
                               sencha-touch-all-debug.js"/>
        </copy>

        <copy file="${framework.target.dir}/sencha-touch-debug.js"
              tofile="${framework.target.dir}/sencha-touch.js"/>
        <copy file="${framework.target.dir}/sencha-touch-all-debug.js"
              tofile="${framework.target.dir}/sencha-touch-all.js"/>

        <propertyfile file="${args.path}/${senchadir}/workspace/sencha.cfg">
            <entry type="string"
                   operation="="
                   key="${framework.name}.dir" 
                   value="$${workspace.dir}/${framework.relative.path}"/>
            <entry type="string"
                   operation="="
                   key="workspace.cmd.version" 
                   value="${cmd.version}"/>
        </propertyfile>
    </target>

    <scriptdef name="x-generate-uuid" language="javascript">
        <attribute name="property" />
        <![CDATA[
            importClass( java.util.UUID );
            project.setProperty(
                attributes.get( "property" ),
                UUID.randomUUID().toString());
        ]]>
    </scriptdef>

    <target name="copy-sdk">
        <copy file="${framework.dir}/resources/css-debug/sencha-touch.css"
              tofile="${args.path}/resources/css/app.css"/>
    </target>

    <!--
        Generates an application structure from templates
        CLI args available as:
        args.name => the application name
        args.path => the target path of the new application
    -->
    <target name="generate-app-impl">
        <x-generate-uuid property="unique.id"/>
        <x-generate dir="${templates.dir}/App" todir="${args.path}">
            <param name="name" value="${args.name}"/>
            <param name="appName" value="${args.name}"/>
            <param name="library" value="${args.library}"/>
            <param name="uniqueId" value="${unique.id}"/>
            <param name="frameworkName" value="${framework.name}"/>
            <param name="frameworkPath" value="${framework.path}"/>
            <param name="senchadir" value="${senchadir}"/>
        </x-generate>

        <mkdir dir="${args.path}/app"/>
        <mkdir dir="${args.path}/app/model"/>
        <mkdir dir="${args.path}/app/view"/>
        <mkdir dir="${args.path}/app/controller"/>
        <mkdir dir="${args.path}/app/store"/>
        <mkdir dir="${args.path}/app/profile"/>
        <mkdir dir="${framework.dir}/resources"/>
        <mkdir dir="${framework.dir}/resources/css"/>
        <mkdir dir="${framework.dir}/resources/images"/>
        <mkdir dir="${framework.dir}/resources/icons"/>
        <mkdir dir="${framework.dir}/resources/sass"/>

        <!-- generate the packager.json file with stbuild -->
        <script language="javascript">
            importPackage(java.io);
            importPackage(com.sencha.util);
            importPackage(com.sencha.command);
            importPackage(com.sencha.logging);
            importPackage(com.sencha.tools.external);

            var _logger = SenchaLogManager.getLogger('app-resolve'),
                sencha = new Sencha(),
                path = project.getProperty('args.path'),
                args = ['package', 'generate', path + '/packager.json'];

            if(!PlatformUtil.isLinux()) {
                _logger.info("Generating new packager.json file using native packager");
                sencha.dispatch(args);
            }

        </script>

        <antcall target="copy-sdk"/>
    </target>

    <!--
        Adds a new theme template application
        args.name => the theme name
        args.cssPath => the path to the css file
    -->
    <target name="generate-theme-impl">
        <fail>Generate Theme is an ExtJS SDK specific command.</fail>
    </target>

    <!--
        Adds a controller class to the application
        CLI args available as:
        args.name => the application name
        args.path => the target path of the new application
    -->
    <target name="generate-controller-impl">
        <x-generate dir="${templates.dir}/Controller" todir="${args.path}/app/controller">
            <load file="${args.path}/app.json"/>
            <param name="name" value="${args.name}"/>
            <param name="controllerName" value="${args.name}"/>
            <param name="controllerFileName" value="${args.filename}"/>
        </x-generate>
        <antcall target="update-app">
            <param name="item" value="${args.name}"/>
            <param name="section" value="controllers"/>
        </antcall>
    </target>

    <!--
        Adds a profile class to the application
        CLI args available as:
        args.name => the application name
        args.path => the target path of the new application
    -->
    <target name="generate-profile-impl">
        <x-generate dir="${templates.dir}/Profile" todir="${args.path}/app/profile">
            <load file="${args.path}/app.json"/>
            <param name="name" value="${args.name}"/>
            <param name="profileName" value="${args.name}"/>
            <param name="profileFileName" value="${args.filename}"/>
        </x-generate>
        <antcall target="update-app">
            <param name="item" value="${args.name}"/>
            <param name="section" value="profiles"/>
        </antcall>
    </target>

    <!--
        Adds a model class to the application
        CLI args available as:
        args.name => the model name
        args.path => the target path of the application
        args.fields => the field definitions to add
        -fields=name:val,other:otherval,...
    -->
    <target name="generate-model-impl">
        <x-generate dir="${templates.dir}/Model" todir="${args.path}/app/model">
            <load file="${args.path}/app.json"/>
            <param name="name" value="${args.name}"/>
            <param name="modelFileName" value="${args.filename}"/>
            <param name="fields" value="${args.fields}"/>
        </x-generate>
        <antcall target="update-app">
            <param name="item" value="${args.name}"/>
            <param name="section" value="models"/>
        </antcall>
    </target>

    <!--
        Adds a form class to the application
        CLI args available as:
        args.name => the form name
        args.path => the target path of the application
        args.fields => the field definitions to add
        -fields=name:val,other:otherval,...
    -->
    <target name="generate-form-impl">
        <x-generate dir="${templates.dir}/Form" todir="${args.path}/app/view">
            <load file="${args.path}/app.json"/>
            <param name="name" value="${args.name}"/>
            <param name="formFileName" value="${args.filename}"/>
            <param name="fields" value="${args.fields}"/>
            <param name="xtype" value="${args.xtype}"/>
        </x-generate>
        <antcall target="update-app">
            <param name="item" value="${args.name}"/>
            <param name="section" value="views"/>
        </antcall>
    </target>

    <!--
        Adds a model class to the application
        CLI args available as:
        args.name => the model name
        args.path => the target path of the application
        args.fields => the field definitions to add
        -fields=name:val,other:otherval,...
    -->
    <target name="generate-view-impl">
        <fail>Generate View is an ExtJS SDK specific command.</fail>
    </target>

    <!--
        Adds mvc class references to the main app.js script
    -->
    <target name="update-app" unless="args.upgrade">
        <property name="app.js.file" value="${args.path}/app.js"/>
        <loadfile property="appData" srcfile="${app.js.file}"/>

        <condition property="newsection" else="false">
            <matches pattern="(?s)^.*${section}\s*\:.*$" string="${appData}"/>
        </condition>

        <condition property="emptysection" else="false">
            <matches
                    pattern="(?s).*${section}\s*\:\s*\[\s*\]"
                    string="${appData}"
                    multiline="true"/>
        </condition>

        <if>
            <equals arg1="${newsection}" arg2="false"/>
            <then>
                <replaceregexp
                        file="${app.js.file}"
                        match="(Ext.application\(\{(\n|\r\n))"
                        replace="\1    ${section}: [&quot;${item}&quot;],${line.separator}${line.separator}"/>
            </then>
            <elseif>
                <equals arg1="${emptysection}" arg2="true"/>
                <then>
                    <replaceregexp
                            file="${app.js.file}"
                            match="(${section}\s*\:\s*\[)"
                            replace="\1&quot;${item}&quot;"/>
                </then>
            </elseif>
            <else>
                <replaceregexp
                        file="${app.js.file}"
                        match="(${section}\s*\:\s*\[)"
                        replace="\1&quot;${item}&quot;,"/>
            </else>
        </if>

    </target>

    <scriptdef name="x-app-upgrade" language="javascript" src="${framework.config.dir}/app-upgrade.js">
        <classpath>
            <pathelement location="${cmd.dir}/lib/ant-contrib-1.0b3.jar"/>
            <pathelement location="${cmd.dir}/sencha.jar"/>
        </classpath>
    </scriptdef>

    <target name="app-upgrade-impl">
        <x-app-upgrade/>
        <echo>Updating Application sencha.cfg</echo>
        <propertyfile file="${app.config.dir}/sencha.cfg">
            <entry type="string"
                   operation="="
                   key="app.cmd.version" 
                   value="${cmd.version}"/>
        </propertyfile>
    </target>

    <target name="app-resolve-impl">
        <script language="javascript">
            importPackage(java.io);
            importPackage(com.sencha.util);
            importPackage(com.sencha.logging);
            importPackage(com.sencha.tools.external);

            var _logger = SenchaLogManager.getLogger('app-resolve'),
                runner = new PhantomJsRunner(),
                args = [
                    PathUtil.join(project.getProperty("basedir"), "dependencies.js"),
                    project.getProperty("args.uri")
                ],
                runnerOut = runner.run(args),
                exitCode = runnerOut.getExitCode(),
                stdout = runnerOut.getOutput();

            if(exitCode > 0) {
                _logger.error("Failed capturing Dependencies");
                _logger.error(stdout);
                throw 'Failed capturing dependencies';
            }

            FileUtil.writeFile(project.getProperty("args.output"), stdout);

        </script>
    </target>

</project>